<!--
	作者：lsd
	时间：2020-4-21
	描述：任务分派
-->
<template>
	<div class="m-view-taskAssignment m-window">
		<!-- 搜索头 -->
		<div class="m-condition">
			<el-form
				:model="formSearch"
				ref="formSearch"
				label-width="90px"
				:inline-message="true"
				label-position="left"
			>
				<el-row :gutter="10">
					<el-col :span="10">
						<el-form-item label="工厂" class="rightItem" style="height: 40px">
							<el-select
								v-model="formSearchApplyList.plantCode"
								filterable
								multiple
								collapse-tags
								:filter-method="filterFactory"
								@change="changeCompany"
								placeholder="请选择工厂"
							>
								<el-option
									v-for="item in optionsFactory"
									:key="item.plantCode"
									:label="item.plantName"
									:value="item.plantCode"
								>
									<span style="float: left">{{ item.plantName }}</span>
									<span style="float: right; color: #8492a6; font-size: 13px">{{ item.plantCode }}</span>
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="采购申请号" class="rightItem">
							<el-input
								v-model.trim="formSearchApplyList.requestNo"
								placeholder="请输入"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="批准日期" class="rightItem">
							<el-date-picker
								v-model="formSearchApplyList.auditDate"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								clearable
								:picker-options="timeRange(formSearchApplyList.auditDateEnd, true)"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-date-picker
							v-model="formSearchApplyList.auditDateEnd"
							clearable
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
							:picker-options="timeRange(formSearchApplyList.auditDate)"
						></el-date-picker>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :span="5">
						<el-form-item label="物料描述" class="rightItem">
							<el-input
								v-model.trim="formSearchApplyList.matName"
								placeholder="请输入"
								clearable
								maxlength="20"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="状态" class="rightItem">
							<el-select v-model="pageState" @change="stateChange" placeholder="请选择状态">
								<el-option
									v-for="item in [{name: '未分派', value: 0}, {name: '已分派', value: 1}]"
									:key="item.value"
									:label="item.name"
									:value="item.value"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6" v-show="pageState == 1">
						<el-form-item label="责任人" class="rightItem">
							<el-select
								v-model="formSearch.handlerList"
								multiple
								collapse-tags
								placeholder="请选择责任人"
							>
								<el-option
									v-for="item in optionsPurchaser"
									:key="item.id"
									:label="item.purcheaserName"
									:value="item.sapNum"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="2" :offset="10" v-show="pageState == 0">
						<el-button type="primary" @click="searchApplyList(true)">查询</el-button>
					</el-col>
					<el-col :span="2" :offset="4" v-show="pageState == 1">
						<el-button type="primary" @click="search">查询</el-button>
					</el-col>
					<el-col :span="2" v-show="pageState == 0">
						<el-button type="primary" @click="save">保存</el-button>
					</el-col>
					<el-col :span="2" v-show="pageState == 1">
						<el-button type="primary" @click="recall">撤回</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<!-- 未分派表单 -->
		<el-row :gutter="2" class="m-task-content m-top2" v-show="pageState == 0">
			<el-col :span="5" class="m-task-content-el-col">
				<div class="m-agTable m-bottom" v-loading="loading" v-show="pageState == 0">
					<ag-grid-component
						ref="agGridComponentPurchaser"
						:tableName="'taskAssignmentTablePh'"
						:getGridOptions="gridOptionsPurchaser"
						:getColumnDefs="columnDefsPurchaser"
						rowSelection="single"
						:isColFit="true"
						:systemInfo="$systemInfo"
					></ag-grid-component>
				</div>
			</el-col>
			<el-col :span="19" class="m-task-content-el-col" v-show="pageState == 0">
				<div class="m-agTable m-bottom" style="margin-left: 15px;" v-loading="loading">
					<ag-grid-component
						ref="agGridComponent"
						:tableName="'taskAssignmentTable'"
						:getGridOptions="gridOptions"
						:getColumnDefs="columnDefs"
						getRowSelection="multiple"
						:isColFit="true"
						:systemInfo="$systemInfo"
					></ag-grid-component>
				</div>
				<!-- 页脚 -->
				<div class="m-page m-task-content-m-page" v-show="pageState == 0">
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="pageInfo.currentPage"
						:page-sizes="[100,200,300,400,500 ]"
						:page-size="pageInfo.pageSize"
						layout="total, sizes, prev, pager, next, jumper"
						:total="total"
					></el-pagination>
				</div>
			</el-col>
		</el-row>
		<!-- 已分派表单 -->
		<div class="m-agTable m-bottom m-top2" v-show="pageState == 1">
			<ag-grid-component
				ref="taskAgGridComponent"
				:tableName="'taskAssignmentTableTK'"
				:getGridOptions="taskGridOptions"
				:getColumnDefs="taskColumnDefs"
				getRowSelection="multiple"
				:isColFit="true"
				:systemInfo="$systemInfo"
			></ag-grid-component>
		</div>
		<!-- 页脚 -->
		<div class="m-page m-task-content-m-page" v-show="pageState == 1">
			<el-pagination
				@size-change="handleSizeChangeTask"
				@current-change="handleCurrentChangeTask"
				:current-page="pageInfoAssignment.currentPage"
				:page-sizes="[100,200,300,400,500 ]"
				:page-size="pageInfoAssignment.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalAssignment"
			></el-pagination>
		</div>

		<!-- 历史记录弹窗 -->
		<history-log :formData="historyData" :dialogVisible="diaShow" @dialogClose="diaShow = false"></history-log>
	</div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import gridOptions from "lesso-common/public/gridOptions";
import historyLog from "./common/dialogSrmHistoryLog";
import Vue from "vue";
/**
 * @group taskAssignment
 * 任务分派
 */
export default {
	name: 'taskAssignment',
	components:{ historyLog },
	data () {
		return {
			//页面状态
			pageState: 0,//0为未分派页面， 1为已分派页面
			//表单数据
			formSearch: {//已分派表
				prState: 1,
				handlerList: '',
			},
			formSearchApplyList: {//未分派表
				state: 0,
				plantCode: '',
				requestNo: '',
				auditDate: new Date(new Date().getTime() - 30 * 24 * 3600 * 1000).Format('yyyy-MM-dd'),
				auditDateEnd: new Date().Format('yyyy-MM-dd'),
				matName: '',
			},
			// 表格数据
			rowData: [],
			rowDataPurchaser: [],
			//表格参数
			gridOptions: '',//采购申请单表
			columnDefs: [],
			gridOptionsPurchaser: '',//采购员表
			columnDefsPurchaser: [],
			columnDefsAssignment: [],//已分派任务
			//下拉框数据
			optionsPurchaser: [],
			optionsFactory: [], //工厂下拉框列表
			optionsTempFactory: [], //工具人，专门用来过滤的
			//页脚参数
			pageInfo: {//采购申请单页脚
				pageSize: 100,
				currentPage: 1,
			},
			total: 0,
			pageInfoPurchaser: {//采购员页脚
				pageSize: 30,
				currentPage: 1,
			},
			totalPurchaser: 0,
			pageInfoAssignment: {//已分派任务页脚
				pageSize: 100,
				currentPage: 1,
			},
			totalAssignment: 0,
			//加载参数
			loading: false,//页面的
			diaShow: false,
			historyData: {}//转派记录表
		}
	},
	beforeMount () {
		//采购订单表
		this.gridOptions = {
			context: {
				componentParent: this
			},
			defaultColDef: {
        sortable: true
			},
			sideBar: {
        toolPanels:[
            {
                id: "columns",
                labelDefault: "Columns",
                labelKey: "columns",
                iconKey: "columns",
                toolPanel: "agColumnsToolPanel"
            }
				]
			},
			rowSelection: "multiple",
			rowDeselection: false,
			rowMultiSelectWithClick:true,
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,//单元格选中,false为选中整行
		};
		//采购订单表
		this.columnDefs = [
			{ checkboxSelection: true, headerCheckboxSelection: true, headerName: "采购申请", field: "requestNo", width: 100 },
			{ headerName: "工厂", field: "plantName", width: 150, },
			{ headerName: "批准日期", field: "auditDate", width: 90 },
			{ headerName: "项目", field: "requestMxno", width: 70 },
			{ headerName: "物料编码", field: "matCode", width: 100 },
			{ headerName: "物料描述", field: "matName", width: 150 },
			{ headerName: "申请数量", field: "requestAmount", width: 95 },
			{ headerName: "单位", field: "unitCode", width: 65 },
			{ headerName: "备注", field: "remark", width: 150 },
			{ headerName: "申请部门", field: "purGroupName", width: 130 },
			{ headerName: "申请者", field: "requester", width: 80 },
			{ headerName: "历史采购员", field: "historyHandlerName", width: 105 },
			{ headerName: "申请日期", field: "sapCreateDate", width: 90, hide: true },
			{ headerName: "物料组", field: "matgroup", width: 95, hide: true },
			{ headerName: "物料组描述", field: "matgroupName", width: 150, hide: true }
		];
		//采购员表
		this.gridOptionsPurchaser = {
			context: {
				componentParent: this
			},
			enableColResize: true,
			rowSelection: "single",
			localeText: localeText,
			suppressRowClickSelection: false,//单元格选中,false为选中整行
		};
		this.columnDefsPurchaser = [
			{ headerName: "采购员", field: "purcheaserName", checkboxSelection: true, width: 160},
			{ headerName: "工厂", field: "plantCode", width: 150 }
		];

		//已分派任务表
		this.taskGridOptions = {
			...this.gridOptions
		};
		let list = [
			{ headerName: "责任人", field: "handlerName", width: 120 },
			{ headerName: "任务号", field: "taskNo", width: 150 },
			{	headerName: "任务状态", field: "state", width: 120,
				cellRenderer: (params) => {
					let tip = ''
					switch (params.value) {
						case 0:
							tip = "<span style='color: red'>未确认</span>";
							break
						case 1:
							tip = "<span style='color: green'>已确认</span>";
							break
						case 2:
							tip = '已拒绝';
							break
						case 3:
							tip = '已转派';
							break
					}
					return tip
				}
			},
			{	headerName: "是否转派", field: "state", width: 120,
				cellRenderer: (params) => {
					let tip = ''
					if (params.value == '3') {
						tip = '是';
					}
					else {
						tip = '否';
					}
					return tip
				}
			},
			{ headerName: "操作时间", field: "createDate", width: 180 },
			{ headerName: "转派记录", width: 120, 
				cellRendererFramework: Vue.extend({
          template: `<span>
						<el-button 
							type="text" 
							class="rendererClass" 
							size="mini" 
							@click="openHistoryDia(params.data)">
              查看
            </el-button>
          </span>`,
          methods: {
            /**
             * @vuese
             * 项目列表的按钮点击事件
             * 
             * @arg row:行数据;
             */
            openHistoryDia( row) {
							this.params.context.componentParent.historyData = row;
							this.params.context.componentParent.diaShow = true;
						},
					}
				})
			}	
		]
		this.taskColumnDefs = this.columnDefs.concat(list)

	},
	mounted () {
		this.getFactoryList(true);
	},
	methods: {
		/**
		 * @vuese
		 * 查询未分派的采购申请方法
		 * 
		 * @arg 参数是布尔值， true就是点击触发，false就是非点击触发
		 */
		searchApplyList (isClick) {
			this.pageInfo.currentPage = isClick ? 1 : this.pageInfo.currentPage
			this.loading = true;
			let param = {
				sapNum: this.$global.user.idmNum,
				...this.formSearchApplyList,
				...this.pageInfo,
				auditFlag: 2,
			};
			delete param.plantCode;
			param.plantCodeList = this.formSearchApplyList.plantCode.toString();

			if (!param.auditDate && param.auditDateEnd) {
				param.auditDate = '1970-01-01';
			}
			if (param.auditDate && !param.auditDateEnd) {
				param.auditDateEnd = this.getNowTime();;
			}

			_Api
				.getPuechaserApplyListByTask(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.rowData = res.data.rows;
						this.total = res.data.total
						this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese 
		 * 查询任务列表
		 * 
		 * @arg 参数是布尔值， true就是点击触发，false就是非点击触发
		 */
		search (isClick) {
			this.loading = true;
			this.pageInfoAssignment.currentPage = isClick ? 1 : this.pageInfoAssignment.currentPage
			let param = {
				...this.formSearch,
				...this.formSearchApplyList,
				...this.pageInfoAssignment
			}
			delete param.plantCode;
			param.plantCodeList = this.formSearchApplyList.plantCode.toString();
			param.handlerList = this.formSearch.handlerList.toString();

			if (!param.auditDate && param.auditDateEnd) {
				param.auditDate = '1970-01-01';
			}
			if (param.auditDate && !param.auditDateEnd) {
				param.auditDateEnd = this.getNowTime();;
			}

			delete param.state
			_Api
				.getTaskList(param)
				.then(res => {
					this.loading = false;
					if (res.data.code == 1) {
						this.$refs.taskAgGridComponent.gridOptions.api.setRowData(res.data.rows);
						this.totalAssignment = res.data.total
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loading = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese 
		 * 撤回
		 */
		recall () {
			//获取选中参数
			let row = this.$refs.taskAgGridComponent.gridOptions.api.getSelectedRows();//选中的任务列表

			//判空
			if (row.length <= 0) {
				this.$alert("提示：请选择一项任务", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt" });
				return
			}
			//判断是否有其他状态的
			if (row.findIndex(e => e.state == 0) > -1) {
				//	this.$alert("选中的任务中有未确认以外的任务，请重新选择！", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt"	});
				//	return
			}
			//填充参数
			let list = [];
			for (let i = 0; i < row.length; i++) {
				let temp = {
					id: row[i].id,
					requestMxno: row[i].requestMxno,
					requestNo: row[i].requestNo,
					modifyerId: this.$global.user.id,
					modifyer: this.$global.user.employeeName//修改人
				}
				list.push(temp)
			}
			this.$confirm(`是否撤回这些任务？`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.recallTask(list)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.$alert('撤回成功！', { showClose: false, confirmButton: "确定", customClass: "success" });
							this.search();
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		/**
		 * @vuese 
		 * 保存方法
		 */
		save () {
			//获取选中参数
			let pRow = this.$refs.agGridComponentPurchaser.gridOptions.api.getSelectedRows();//采购员
			let aRow = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();

			//判空
			if (pRow.length <= 0) {
				this.$alert("提示：请选择采购员", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt" });
				return
			}
			if (aRow.length <= 0) {
				this.$alert("提示：请选择采购申请单", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt" });
				return
			}

			//匹配是否多个工厂
			if( aRow.length>1 ){
				for(let i = 1; i < aRow.length; i++){
					if( aRow[0].plantCode != aRow[1].plantCode ){
						this.$alert("提示：请选择同一个工厂", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt" });
						return
					}
				}
			}

			//匹配人是否对应这个工厂
			if( pRow[0].plantCode.indexOf(aRow[0].plantCode) == -1 ){
				this.$alert("提示：工厂和人要匹配", { showClose: false, confirmButtonText: "确定", customClass: "alertPrompt" });
						return
			}

			//填充参数
			let list = [];
			let creatorId = this.$global.user.id;
			let creator = this.$global.user.employeeName//创建人
			for (let i = 0; i < aRow.length; i++) {
				let temp = {
					requestId: aRow[i].id,
					requestNo: aRow[i].requestNo,
					requestMxno: aRow[i].requestMxno,
					handler: pRow[0].sapNum,
					handlerName: pRow[0].purcheaserName,
					creatorId,
					creator
				}
				list.push(temp)
			}

			this.$confirm(`是否派遣这 ${aRow.length} 任务给  ${pRow[0].purcheaserName}  ？`, "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				this.loading = true;
				_Api
					.addTask(list)
					.then(res => {
						this.loading = false;
						if (res.data.code == 1) {
							this.searchApplyList();
							this.$alert('派遣成功！', { showClose: false, confirmButton: "确定", customClass: "success" });
						} else {
							this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
						}
					})
					.catch(err => {
						this.loading = false;
						this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					});
			})
		},

		/**
		 * @vuese 
		 * 根据工厂获取全部采购员方法
		 */
		getPurcheaserList () {
			let plantCodeList = this.formSearchApplyList.plantCode.toString();
			if ( !plantCodeList ) {
				return
			}
			this.loadingDia = true;
			_Api
				.getAllPurchaserList({ plantCodeList })
				.then(res => {
					this.loadingDia = false;
					if (res.data.code == 1) {
						this.optionsPurchaser = res.data.rows;
						this.rowDataPurchaser = res.data.rows;
						this.$refs.agGridComponentPurchaser.gridOptions.api.setRowData(res.data.rows)
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loadingDia = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 根据账号获取工厂列表方法
		 * 
		 * @arg flag是布尔值，true就是给搜索框的工厂添加默认值，false不添加默认值
		 */
		getFactoryList (flag) {
			this.loadingDia = true;
			_Api
				.getFactoryListBySapNum({ sapNum: this.$global.user.idmNum })
				.then(res => {
					this.loadingDia = false;
					if (res.data.code == 1) {
						this.optionsFactory = res.data.rows;
						this.optionsTempFactory = res.data.rows;
						if (this.optionsFactory.length >= 1 && flag) { //添加默认值
							this.formSearchApplyList.plantCode = [this.optionsFactory[0].plantCode];		
							this.searchApplyList();
						}
						this.getPurcheaserList();
					} else {
						this.$alert(res.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
					}
				})
				.catch(err => {
					this.loadingDia = false;
					this.$alert(err.data.info, { showClose: false, confirmButton: "确定", customClass: "alertFailure" });
				});
		},

		/**
		 * @vuese
		 * 采购申请列表改变页脚总条数方法
		 * 
		 * @arg 参数是 int 值，代表一页有多少条数据
		 */
		handleSizeChange (val) {
			this.pageInfo.pageSize = val;
			this.pageInfo.currentPage = 1;
			this.searchApplyList();
		},

		/**
		 * @vuese
		 * 采购申请列表翻页方法
		 * 
			 * @arg 参数是 int 值，代表页数
		 */
		handleCurrentChange (val) {
			this.pageInfo.currentPage = val;
			this.searchApplyList();
		},

		/**
		 * @vuese
		 * 任务列表改变页脚总条数方法
		 * 
		 * @arg 参数是 int 值，代表一页有多少条数据
		 */
		handleSizeChangeTask (val) {
			this.pageInfoAssignment.pageSize = val;
			this.pageInfoAssignment.currentPage = 1;
			this.search();
		},

		/**
		 * @vuese
		 * 任务列表翻页方法
		 * 
		 * @arg 参数是 int 值，代表页数
		 */
		handleCurrentChangeTask (val) {
			this.pageInfoAssignment.currentPage = val;
			this.search();
		},
		/**
		 * @vuese
		 * 日期可选范围
			 * 
			 * @arg startTime参数是时间， 代表为最小时间； flag是布尔值， true为开始时间范围， false为结束时间范围
		 */
		timeRange (startTime, flag) {
			return {
				disabledDate (time) {
					let tempTime = new Date(startTime).getTime() || 0;
					let minTime = time.getTime() + 24 * 60 * 60 * 1000;

					if (tempTime == 0) {
						return time.getTime() > Date.now();
					}
					else if (flag) {
						return time.getTime() > tempTime;
					}
					else {
						return minTime < tempTime || time.getTime() > Date.now();
					}
				}
			}
		},

		/**
		 * @vuese
		 * 切换状态
		 * 
		 * @arg 参数是int值，用来切换页面状态
		 */
		stateChange (val) {
			if (val == 1)
				this.search();
			else {
				this.searchApplyList();
				this.getFactoryList();
			}
		},

		/**
		 * @vuese
		 * 切换工厂
		 */
		changeCompany () {
			if (this.pageState == 1)
				this.search();
			else {
				this.searchApplyList();
				this.getFactoryList();
			}
		},

		/**
		 * @vuese
		 * 过滤工厂
		 * 
		 * @arg value:传入的是检索值, 用于过滤
		 */
		filterFactory (value) {
			if (value != '') {
				this.optionsFactory = this.optionsTempFactory.filter(item => item.plantCode.indexOf(value) > -1 || item.plantName.indexOf(value) > -1)
			} else {
				this.optionsFactory = this.optionsTempFactory
			}
		}
	}
}
</script>

<style lang="less">
.m-view-taskAssignment {
	.el-select {
		overflow: hidden;
		.el-select__tags{
			overflow: hidden;
		}
	}
	.el-form {
		.el-form-item {
			margin-bottom: 0px;
		}
	}
	.m-task-content {
		position: absolute;
		width: 100%;
		bottom: 0px;
		.m-task-content-el-col {
			position: relative;
			height: 100%;
			.m-agTable {
				position: absolute;
				top: 0px;
				bottom: 35px;
				left: 0px;
				right: 0px;
			}
			.m-task-content-m-page {
				margin-left: 16px;
			}
		}
	}
}
</style>